package com.yupi.yupao.service.logic.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserAttention;
import com.yupi.yupao.service.UserAttentionService;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.service.logic.UserLogicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author yyzhang
 * @version 1.0
 */
@Service
@Slf4j
public class UserLogicServiceImpl implements UserLogicService {
@Resource
private UserService userService;
@Resource
private UserAttentionService userAttentionService;
    @Override
    public Boolean addAttention(Long attentionId, HttpServletRequest request) {
       Long id = userService.getLoginUser(request).getId();
       if(id==null||id<=0){
           throw new BusinessException(ErrorCode.NOT_LOGIN);
       }
        UserAttention userAttention = new UserAttention();
       userAttention.setUserId(id);
       userAttention.setUserAttentionId(attentionId);
       boolean save = userAttentionService.save(userAttention);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户关注表插入失败");
        }
        return save;
    }

    @Override
    public Boolean deleteAttention(Long attentionId, HttpServletRequest request) {
        Long id = userService.getLoginUser(request).getId();
        if(id==null||id<=0){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        final QueryWrapper<UserAttention> userAttentionQueryWrapper = new QueryWrapper<>();
        userAttentionQueryWrapper.eq("userId",id);
        userAttentionQueryWrapper.eq("attentionId",attentionId);
        final UserAttention one = userAttentionService.getOne(userAttentionQueryWrapper);
        if(one!=null){
            final boolean b = userAttentionService.removeById(one.getId());
            if(!b){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"取消关注失败");
            }
            return b;
        }
        return true;

    }
}
